package ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.manager.spring.impl;

import ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.manager.Manager;
import ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.manager.ManagerConstructArgs;
import ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.manager.ManagerFactory;
import ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.manager.spring.ManagerSpringFactory;
import ace.cmp.spring.util.core.SpringUtils;
import org.springframework.beans.factory.ObjectProvider;

/**
 * @author caspar
 */
public class ManagerSpringFactoryImpl implements ManagerSpringFactory {

  private final ManagerFactory managerFactory;
  private final SpringUtils springUtils;

  public ManagerSpringFactoryImpl(
      ManagerFactory managerFactory, SpringUtils springUtils) {
    this.managerFactory = managerFactory;
    this.springUtils = springUtils;
  }

  @Override
  public <EntityT, IdT> Manager<EntityT, IdT> getOrCreate(ManagerConstructArgs<EntityT, IdT> args) {
    ObjectProvider<Manager<EntityT, IdT>> objectProvider = springUtils.getBeanByClassWithGenericsObjectProvider(
        Manager.class, args.getEntityClass(), args.getIdClass()
    );
    return objectProvider.getIfAvailable(() -> this.managerFactory.getOrCreate(args));
  }
}
